package com.example.operation.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.operation.domin.Admin;
import com.example.operation.dto.AdminDto;
import com.example.operation.mapper.AdminMapper;
import com.example.operation.service.AdminService;
import com.github.xiaoymin.knife4j.core.util.StrUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class AdminServiceImpl extends ServiceImpl<AdminMapper, Admin> implements AdminService{

    @Autowired
    private AdminMapper adminMapper;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void insertAd(AdminDto adminDto) {
        Admin admin = new Admin();
        LambdaQueryWrapper<Admin> adminLambdaQueryWrapper = new QueryWrapper<Admin>()
                .lambda().eq(Admin::getUsername, adminDto.getUsername());
        Integer count = adminMapper.selectCount(adminLambdaQueryWrapper);
        if(count > 0) {
            throw new RuntimeException("用户名称不能重复");
        }
        BeanUtils.copyProperties(adminDto,admin);
        adminMapper.insert(admin);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Integer updateAd(AdminDto adminDto) {
        Admin admin = new Admin();
        LambdaUpdateWrapper<Admin> lambda = new UpdateWrapper<Admin>()
                .lambda().eq(Admin::getUsername,adminDto.getUsername());
        Integer count = adminMapper.selectCount(lambda);
        if(count ==0) {
            throw new RuntimeException("当前用户不存在，请确认您要修改的管理员账号是否正确");
        }
        BeanUtils.copyProperties(adminDto, admin);
        return adminMapper.update(admin,lambda);
    }

    @Override
    public Admin selectById(Integer id) {
        return adminMapper.selectById(id);
    }

    @Override
    public Page<Admin> pageAd(Integer pageNumber, Integer pageSize, String username) {
        Page<Admin> adminDtoPage = new Page<>(pageNumber,pageSize);
        LambdaQueryWrapper<Admin> eq = new QueryWrapper<Admin>()
                .lambda().eq(Admin::getState,1)
                .like(StrUtil.isNotBlank(username),Admin::getUsername,username);
        return adminMapper.selectPage(adminDtoPage,eq);

    }
}
